(function(win){
	var Z = win.Z,
		BundleList = Z.BundleList,
		Bundle = Z.Bundle,
		clients = {},
		languages = {
			'0' : ['th', '繁体'],
			'1' : ['zh', '简体'],
			'2' : ['en', '英语'],
			'3' : ['ru', '俄语'],
			'4' : ['jp', '日语'],
			'5' : ['pt', '葡萄牙'],
			'6' : ['sp', '西班牙'],
			'7' : ['de', '德语'],
			'8' : ['fr', '法语'],
			'9' : ['kr', '韩语'],
			'10' : ['tl', '泰语'],
			'11' : ['id', '印尼'],
			'12' : ['tr', '土耳其'],
			'13' : ['vn', '越南语'],
			'14' : ['ng', '尼日利亚（英语）'],
			'15' : ['ar', '阿拉伯'],
			'16' : ['it','意大利'],
			'17' : ['pl','波兰语'],
			'18' : ['se', '瑞典语'],
			'19' : ['hu', '匈牙利语'],
			'20' : ['gr', '希腊语']
		},
		bundle = new Bundle({'tmpl' : 'debug'});

	bundle.addEvent('select[name="apiType"]', 'change', function(){
		loadClients($(this).val());
	});

	bundle.addEvent('select[name="env"]', 'change', function(){
		var api = bundle.find('select[name="api"]').val();
		fillUrl($(this).val(), clients[api]);
	});

	bundle.addEvent('a.save-url', 'click', function(){
		$.cookie('debug-url', bundle.find('input[name="url"]').val());
		return false;
	});

	bundle.addEvent('select[name="api"]', 'change', function(){
		var client = clients[$(this).val()],
			env = bundle.find('select[name="env"]').val();

		bundle.find('input[name="sigKey"]').val(client['sig']);
		bundle.find('input[name="unid"]').val(client['unid']);
		bundle.find('input[name="sid"]').val(client['sid']);
		bundle.find('input[name="hashKey"]').val(client['verify']);
		fillUrl(env, client);
	});

	bundle.addEvent('dd.expand a', 'click', function(){
		bundle.find('dd.expand ~ dd').toggle();
		$(this).html(bundle.find('dd.expand ~ dd:visible').length ? 'Pick Up' : 'Expand');
	});

	bundle.addEvent('select[name="verifyType"]', 'change', function(){
		var xtunnelverify = $(this).parent().next().children().eq(0);
		if($(this).val() == 0){
			xtunnelverify.hide();
		}else{
			xtunnelverify.show();
		}
	});

	bundle.addEvent('form', 'change', 'select[name="class"]', function(){
		loadMethods($(this).val());
	});

	bundle.addEvent('form', 'change', 'select[name="method"]', function(){
		switch ($(this).prev().val() + '.' + $(this).val()) {
			case 'Goods.get':
				bundle.find('textarea[name="param"]').val("{\n\t\"version\":\"0\"\n}");
				break;
			case 'Reputation.getInfo':
				bundle.find('textarea[name="param"]').val("{\n\t\"field\":\"31\"\n}");
				break;
			case 'Tables.getArenaMatchServer':
				bundle.find('textarea[name="param"]').val("{\n\t\"round\":\"3\"\n}");
				break;
			default:
				bundle.find('textarea[name="param"]').val("");
				break;
		}
	});	

	bundle.addEvent('form', 'submit', function(){
		var i,l,loading = Z.loading(),
			dataArray = $(this).serializeArray(),
			request = {},
			sortDataArray;
			
		sortDataArray = dataArray.sort(function(a, b) {
			return a['name'].localeCompare(b['name']);
		});
		
		l = sortDataArray.length;
		for(i = 0;i < l;i += 1) {
			request[sortDataArray[i]['name']] = sortDataArray[i]['value'];
		}
		
		$.ajax({
			'type' : 'post',
			'url' : Z.url('php/index.php?controller=proxy&action=debug'),
			'data' : $(this).serialize(),
			'dataType' : 'json',
			'success' : function(data){
				request['method'] = request['class'] + '.' + request['method'];
				delete(request['class']);
				delete(request['env']);
				delete(request['verifyType']);
				delete(request['apiType']);
				bundle.find('div.result').html(Z.format({'request' : request, 'response' : data}));
				bundle.find('div.result dd.key:first a').trigger('click');
				loading.close();
			},
			'error' : function(jqXHR, textStatus, errorThrown){
				bundle.find('div.result').html(jqXHR.responseText);
				loading.close();
			}
		});
		return false;
	});

	bundle.onload = function(){
		var type = bundle.find('select[name="apiType"]').val();
		Z.Form.fillSelect(bundle.find('select[name="language"]'), languages, function(i, item){
			return [i, '['+item[0] + '] ' + item[1]];
		});

		loadClients(type, loadFiles);
	};

	BundleList.append(bundle);

	function loadClients(type, cb){
		Z.ajax({
			'url' : Z.url('php/index.php?controller=client&action=records'),
			'data' : {'pageSize' : 100, 'type' : type, 'orderField' : 3, 'flag' : 1},
			'success' : function(data){
				Z.Form.fillSelect(bundle.find('select[name="api"]'),data.records, function(i, item){
					var padApi = item.api < 10 ? ('0' + item.api) : item.api;
					return [item.api, '[' + padApi + '] ' + item.name];
				});

				for(var i=0, l = data.records.length; i < l ;i++){
					var client = data.records[i],
						api = client.api;
					delete(client.api);
					clients[api] = client;
				}

				bundle.find('select[name="api"]').trigger('change');
				
				(cb || function(){})();
			}
		});
	}

	function loadFiles(){
		var loading = Z.loading();
		Z.ajax({
			'url' : Z.url('php/index.php?controller=proxy&action=files'),
			'success' : function(data){
				Z.Form.fillSelect(bundle.find('select[name="class"]'),data, function(i, item){
					var name = item.replace('.php', '');
					return [name, name];
				});
				bundle.find('select[name="class"]').trigger('change');
				loading.close();
			}
		});
	}

	function loadMethods(className){
		var loading = Z.loading();
		Z.ajax({
			'url' : Z.url('php/index.php?controller=proxy&action=methods'),
			'data' : {'class' : className},
			'success' : function(data){
				Z.Form.fillSelect(bundle.find('select[name="method"]'),data, function(i, item){
					return [item, item];
				});
				loading.close();
			}
		});
	}

	function fillUrl(env, client){
		var ip = $('#left li#user-info span:eq(0)').html();
		var url = 'http://' + ip + '/texas/api/api.php';
		switch(env){
			case '0':
				if(typeof $.cookie('debug-url') != 'undefined')
					url = $.cookie('debug-url');
			break;
			case '1':
				url = 'http://' + client.no3 + '/api/api.php';
			break;
			case '2':
				url = 'http://' + client.url + '/api/api.php';
			break;
		}
		bundle.find('input[name="url"]').val(url);
	}
})(window);